package com.yylending.las.lending;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.tbruyelle.rxpermissions.Permission;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.yyfax.common.CLog;
import com.yyfax.common.toast.CompatToast;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.*;
import com.yylending.las.authority.login.LoginActivity;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.location.LocationPresenter;
import com.yylending.las.common.location.entity.Location;
import com.yylending.las.common.utils.PermissionUtil;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.common.widgets.InviteCodeVerifyDialog;
import com.yylending.las.common.widgets.RedDotView;
import com.yylending.las.common.widgets.TelephoneTextView;
import com.yylending.las.lending.quota.ApplyQuotaActivity;
import com.yylending.las.lending.quota.myquota.MyQuotaModel;
import com.yylending.las.lending.quota.myquota.MyQuotaPresenter;
import com.yylending.las.main.InviteCodeVerifyPresenter;
import com.yylending.las.main.MainActivity;
import com.yylending.las.main.MainController;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 借钱页面-未获取额度
 * Created by laixj on 2017/5/22.
 * Copyright ©2017 www.yylending.com. All Rights Reserved.
 */

public class NotApplyFragment extends BaseFragment implements LocationPresenter.View, MyQuotaPresenter.View,
		InviteCodeVerifyPresenter.View {

	static final String TAG = NotApplyFragment.class.getSimpleName();

	private static final int REQUEST_CODE_GPS = 100;

	static final int LOADER_ID_MY_QUOTA = 1;
	static final int LOADER_ID_LOCATE = 2;
	private static final int LOADER_ID_SUBMIT_INVITE_CODE = 1001;
	static final String ARG_APPLY_STATUS = "arg_apply_status";
	static final String ARG_LOCATION = "arg_location";

	Unbinder unbinder;
	@BindView(R.id.title_left_iv)
	ImageView mTitleLeftIv;
	@BindView(R.id.title_tv)
	TextView mTitleTv;
	@BindView(R.id.title_right_tv)
	TextView mTitleRightTv;
	@BindView(R.id.title_right_iv)
	ImageView mTitleRightIv;
	@BindView(R.id.layout_title_bar)
	RelativeLayout mLayoutTitleBar;
	@BindView(R.id.need_apply_quota_btn)
	Button mNeedApplyQuotaBtn;
	@BindView(R.id.lending_notice_tv)
	TextView mLendingNoticeTv;
	@BindView(R.id.service_phone_tv)
	TelephoneTextView mServicePhoneTv;
	@BindView(R.id.red_dot_view)
	RedDotView mRedDotView;

	private LocationPresenter mLocationPresenter;
	private MyQuotaPresenter mMyQuotaPresenter;
	private InviteCodeVerifyPresenter mInviteCodeVerifyPresenter;
	/**
	 * 额度状态
	 */
	private MyQuotaModel.ApplyStatus mApplyStatus;
	/**
	 * 定位间隔不大于10分钟则不重新定位
	 */
	private long mLocateGap = 600000;
	private Location mLocation;
	InviteCodeVerifyDialog mCodeVerifyDialog;

	public static BaseFragment newInstance(MyQuotaModel.ApplyStatus status, Location location) {
		BaseFragment fragment = new NotApplyFragment();
		Bundle args = new Bundle();
		args.putParcelable(ARG_APPLY_STATUS, status);
		args.putParcelable(ARG_LOCATION, location);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		getLoaderManager().initLoader(LOADER_ID_MY_QUOTA, null, this);
		getLoaderManager().initLoader(LOADER_ID_LOCATE, null, this);
		getLoaderManager().initLoader(LOADER_ID_SUBMIT_INVITE_CODE, null, this);
	}

	@Override
	public void onDetach() {
		dismissLoading();
		getLoaderManager().destroyLoader(LOADER_ID_MY_QUOTA);
		getLoaderManager().destroyLoader(LOADER_ID_LOCATE);
		getLoaderManager().destroyLoader(LOADER_ID_SUBMIT_INVITE_CODE);
		super.onDetach();
	}

	@Override
	public void onStart() {
		super.onStart();
		Global.setThirdPartyPageOpenedFlag(false);
		//mLocationPresenter.attach(this);
	}

	@Override
	public void onStop() {
		super.onStop();
		//mLocationPresenter.detach();
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getArguments();
		if (bundle != null) {
			mApplyStatus = bundle.getParcelable(ARG_APPLY_STATUS);
			mLocation = bundle.getParcelable(ARG_LOCATION);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.view_stub_did_not_get_limit, container, false);
		unbinder = ButterKnife.bind(this, rootView);
		EventAgent.register(this);
		initView();
		return rootView;
	}

	private void initView() {
		mTitleLeftIv.setImageResource(R.drawable.ic_home_help);
		mTitleTv.setText(R.string.tab_lend);
		mTitleRightIv.setImageResource(R.drawable.ic_message_white);
		mServicePhoneTv.setPageNo(Constants.PAGE_NO_MAIN_ACTIVITY);
		MainController.initRedDot(mRedDotView);
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_MY_QUOTA:
				mMyQuotaPresenter = (MyQuotaPresenter) data;
				mMyQuotaPresenter.attach(this);
				break;
			case LOADER_ID_LOCATE:
				mLocationPresenter = (LocationPresenter) data;
				mLocationPresenter.attach(this);
				break;
			case LOADER_ID_SUBMIT_INVITE_CODE:
				mInviteCodeVerifyPresenter = (InviteCodeVerifyPresenter) data;
				mInviteCodeVerifyPresenter.attach(this);
				mCodeVerifyDialog = ((MainActivity) getActivity()).createInviteCodeDialog();
				mCodeVerifyDialog.setInviteCodeVerifyPresenter(mInviteCodeVerifyPresenter);
				break;
			default:
				break;
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_MY_QUOTA:
				return new PresenterLoader<>(getActivity(), new MyQuotaPresenter.Generator());
			case LOADER_ID_LOCATE:
				return new PresenterLoader<>(getActivity(), new LocationPresenter.Generator());
			case LOADER_ID_SUBMIT_INVITE_CODE:
				return new PresenterLoader<>(getActivity(), new InviteCodeVerifyPresenter.Generator());

			default:
				return null;
		}
	}

	@Override
	public void onDestroyView() {
		mServicePhoneTv.dismissDialog();
		EventAgent.unregister(this);
		super.onDestroyView();
		unbinder.unbind();
	}

	@Override
	public void onLocateSuccess(Location location) {
		dismissLoading();
		CLog.i(TAG, "NotApplyFragment页面定位成功");
		mLocation = location;
		getInviteCodeStatus();

	}

	@Override
	public void onLocateFail(boolean noPermission) {
		CLog.i(TAG, "定位失败");
		dismissLoading();
		if (noPermission) {
			showNeedLocationPermission();
		} else {
			if (com.yyfax.infrastructure.Constants.isConnected) {
				if(PermissionUtil.isGpsOPen(getActivity())){
					if(PermissionUtil.isSdkUnderM()){
						showNeedLocationPermission();
					}else{
						showToast(R.string.locate_need_retry);
					}
				}else{
					showTwoBtnDialog(R.string.gps_permission_hint, R.string.go_to_settings, R.string.cancel, new CommonDialog.ButtonClickListener() {
						@Override
						public void onCancel(CommonDialog dialog) {
							dialog.dismiss();
						}

						@Override
						public void onConfirm(CommonDialog dialog) {
							//忽略手势密码
							Global.setThirdPartyPageOpenedFlag(true);
							//跳转GPS设置界面
							Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							startActivityForResult(intent, REQUEST_CODE_GPS);
							dialog.dismiss();
						}
					}, true);
				}
			} else {
				showToast(R.string.locate_error_due_to_network);
			}
		}
	}

	private void showNeedLocationPermission(){
		showTwoBtnDialog(getString(R.string.location_permission_hint, getString(R.string.app_name)), getString(R.string.go_to_settings), getString(R.string.cancel), new CommonDialog.ButtonClickListener() {
			@Override
			public void onCancel(CommonDialog dialog) {
				dialog.dismiss();
			}

			@Override
			public void onConfirm(CommonDialog dialog) {
				//忽略手势密码
				com.yylending.las.Global.setThirdPartyPageOpenedFlag(true);
				Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
				startActivity(intent);
				dialog.dismiss();
			}
		}, true);
	}

	@Override
	public void getInviteCodeStatusSuccess(boolean hasInviteCode) {
		if (hasInviteCode){
			gotoApplyQuotaActivity();
		}else {
			mCodeVerifyDialog.clearInviteCodeEdt();
			mCodeVerifyDialog.show();
		}
	}

	@Override
	public void getInviteCodeStatusFailed(String tips) {
		CompatToast.showShortToast(getActivity(), tips);
	}

	@Override
	public void submitInviteCodeSuccess() {
		YJKD.hideInputWindow(getActivity());
		dismissCodeVerifyDialog();
		gotoApplyQuotaActivity();
	}

	private void dismissCodeVerifyDialog() {
		if (mCodeVerifyDialog != null && mCodeVerifyDialog.isShowing()) {
			mCodeVerifyDialog.dismiss();
			mCodeVerifyDialog = null;
		}
	}

	@Override
	public void submitInviteCodeFailed() {
		mCodeVerifyDialog.setInviteCodeErrorTips();
	}

	private void showNeedPermission(String msg) {
		showOneBtnDialog(msg, getString(R.string.got_it));
	}

	@Override
	public void showDialog() {
		showLoading(true);
	}

	@Override
	public void dismissDialog() {
		dismissLoading();
	}

	@OnClick({R.id.need_apply_quota_btn, R.id.title_left_iv, R.id.title_right_iv, R.id.lending_notice_tv})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.need_apply_quota_btn:
				StatService.onEvent(getContext(), StatIDSet.EVENT_ID_HOME_PAGE_TO_OBTAIN_CREDITS);
				if (!YJKD.login()) {
					LoginActivity.start((RxAppCompatActivity) getActivity());
					return;
				}
				if (null != mApplyStatus && Constants.QUOTA_STATUS_HAVE_LOAN_OTHER.equals(mApplyStatus.amountState)) {
					showOneBtnDialog(R.string.have_loan_on_the_way, R.string.got_it);
					return;
				}
				showLoading(true);
				mMyQuotaPresenter.myQuota();
				break;
			case R.id.title_left_iv:
				EventAgent.post(new QuotaEvent.PageJumpEvent(QuotaEvent.PageJumpEvent.QUOTA_JUMP_HELP_PAGE, Constants.PAGE_NO_MAIN_ACTIVITY));
				break;
			case R.id.title_right_iv:
				EventAgent.post(new QuotaEvent.PageJumpEvent(QuotaEvent.PageJumpEvent.QUOTA_JUMP_MESSAGE_PAGE, Constants.PAGE_NO_MAIN_ACTIVITY));
				MainController.hideRedDot(mRedDotView);
				break;
			case R.id.lending_notice_tv:
				EventAgent.post(new QuotaEvent.ShowLoanNoticeEvent(QuotaEvent.ShowLoanNoticeEvent.QUOTA_SHOW_LOAN_NOTICE, Constants.PAGE_NO_MAIN_ACTIVITY));
				break;
		}
	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				case Manifest.permission.ACCESS_COARSE_LOCATION:
					if (permission.granted) {
						mLocationPresenter.startLocation(false);
					} else {
						dismissLoading();
						showNeedLocationPermission();
					}
					break;
				default:
					break;
			}

		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {

		}
	};

	private void getInviteCodeStatus(){
		mInviteCodeVerifyPresenter.getInviteCodeStatus();
	}

	private void gotoApplyQuotaActivity(){
		ApplyQuotaActivity.start(getActivity(), mLocation);
	}

	@Override
	public void showLoanPage(int page, MyQuotaModel.ApplyStatus result) {
		if (Constants.PAGE_NOT_APPLY == page) {
			if(null != mLocation && System.currentTimeMillis() - mLocation.lastTime < mLocateGap){//定位时间间隔小于指定时间，不再去定位
				dismissLoading();
				getInviteCodeStatus();
			}else{
				PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
			}
		} else {
			result.page = page;
			EventAgent.post(new QuotaEvent.RefreshStatusEvent(QuotaEvent.RefreshStatusEvent.QUOTA_REFRESH, result));
		}
	}

	@Override
	public void getStatusFail(String msg) {
		dismissLoading();
	}

	@Override
	public void creditReportingOutdated() {

	}

	/**
	 * 定位成功通知
	 *
	 * @param event 会话超时event
	 */
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void locateSuccess(QuotaEvent.LocateSuccessEvent event) {
		switch (event.id) {
			case QuotaEvent.LocateSuccessEvent.QUOTA_LOCATE_SUCCESS:
				mLocation = event.location;
				break;
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onRedDotShowEvent(QuotaEvent.ShowRedDotEvent event) {
		mRedDotView.setVisibility(View.VISIBLE);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onLoanStatusResult(QuotaEvent.RefreshStatusEvent event) {
		switch (event.id) {
			case QuotaEvent.Event.QUOTA_REFRESH_NOT_APPLY:
				CLog.i(TAG, "只更新状态--");
				mApplyStatus = event.mApplyStatus;
				break;
		}
	}
}